package com.hskn.hss.module.materialAppli.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hskn.hss.core.utils.LoginUtils;
import com.hskn.hss.entity.AjaxResult;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.materialAppli.entity.TlMaterialApplication;
import com.hskn.hss.module.materialAppli.mapper.TlMaterialApplicationMapper;
import com.hskn.hss.module.materialAppli.service.ITlMaterialApplicationService;
import com.hskn.hss.module.materialDetail.entity.TlMaterialDetail;
import com.hskn.hss.module.materialDetail.service.ITlMaterialDetailService;
import com.hskn.hss.module.outstorageCfg.entity.TlOutStorageCfg;
import com.hskn.hss.module.outstorageCfg.mapper.TlOutStorageCfgMapper;
import com.hskn.hss.module.userdepart.entity.SysUserDepart;
import com.hskn.hss.module.userdepart.mapper.SysUserDepartMapper;
import com.hskn.hss.utils.AuthoritySqlUtils;
import com.hskn.hss.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hskn
 * @since 2021-05-08
 */
@Service
public class TlMaterialApplicationServiceImpl extends ServiceImpl<TlMaterialApplicationMapper, TlMaterialApplication> implements ITlMaterialApplicationService {

    @Resource
    TlMaterialApplicationMapper tlMaterialApplicationMapper;
    @Resource
    SysUserDepartMapper sysUserDepartMapper;
    @Autowired
    ITlMaterialDetailService tlMaterialDetailService;
    @Resource
    TlOutStorageCfgMapper tlOutStorageCfgMapper;
    @Autowired
    AuthoritySqlUtils authoritySqlUtils;

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class}) //添加事务
    public AjaxResult insert(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        TlMaterialApplication tlMaterialApplication = params.getObject("data", TlMaterialApplication.class);
        QueryWrapper<SysUserDepart> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserDepart::getUserid, uid);
        String deptid = sysUserDepartMapper.selectOne(queryWrapper).getDepid();
        tlMaterialApplication.setSerialnumber(StringUtils.Serialnumber());
        tlMaterialApplication.setStatus("0");
        tlMaterialApplication.setApplicationperson(uid);
        tlMaterialApplication.setApplicationtime(new Date());
        tlMaterialApplication.setId(StringUtils.uuid());
        tlMaterialApplication.setDeptid(deptid);
        tlMaterialApplication.setApplicationtotlnum(tlMaterialApplication.getDateils().size());
        int applicationnum = 0;
        //添加对应的 明细
        for (TlMaterialDetail tlMaterialDetail : tlMaterialApplication.getDateils()) {
            tlMaterialDetail.setId(StringUtils.uuid());
            tlMaterialDetail.setMaterialid(tlMaterialApplication.getId());
            tlMaterialDetail.setSerialnumber(tlMaterialApplication.getSerialnumber());
            applicationnum += tlMaterialDetail.getItemnum();
            JSONObject dateilParam = new JSONObject().fluentPut("data", tlMaterialDetail);
            try {
                tlMaterialDetailService.insert(dateilParam);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("报错ERROR", e);
                return AjaxResult.fail("明细表添加失败，请稍后再试");
            }
        }
        tlMaterialApplication.setApplicationnum(applicationnum);
        int i = tlMaterialApplicationMapper.insert(tlMaterialApplication);
        boolean flag = i > 0 ? true : false;

        if (flag) {
            return AjaxResult.success("操作成功");
        } else {
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }


    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class}) //添加事务
    public AjaxResult update(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        TlMaterialApplication jsonData = params.getObject("data", TlMaterialApplication.class);
        TlMaterialApplication tlMaterialApplication = tlMaterialApplicationMapper.selectById(jsonData.getId());
        tlMaterialApplication.setApplicationreason(jsonData.getApplicationreason());
        tlMaterialApplication.setDateils(jsonData.getDateils());
        tlMaterialApplication.setFileurl(jsonData.getFileurl());
        tlMaterialApplication.setUpdateby(uid);
        tlMaterialApplication.setUpdatetime(new Date());
        tlMaterialApplication.setApplicationtotlnum(tlMaterialApplication.getDateils().size());
        int applicationnum = 0;

        //添加对应的 明细
        tlMaterialDetailService.deleteByMap(tlMaterialApplication.getId());
        for (TlMaterialDetail tlMaterialDetail : tlMaterialApplication.getDateils()) {
            tlMaterialDetail.setId(StringUtils.uuid());
            tlMaterialDetail.setMaterialid(tlMaterialApplication.getId());
            tlMaterialDetail.setSerialnumber(tlMaterialApplication.getSerialnumber());
            applicationnum += tlMaterialDetail.getItemnum();
            JSONObject dateilParam = new JSONObject().fluentPut("data", tlMaterialDetail);
            try {
                tlMaterialDetailService.insert(dateilParam);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("报错ERROR", e);
                return AjaxResult.fail("明细表添加失败，请稍后再试");
            }
        }
        tlMaterialApplication.setApplicationnum(applicationnum);
        int i = tlMaterialApplicationMapper.updateById(tlMaterialApplication);
        boolean flag = i > 0 ? true : false;

        if (flag) {
            return AjaxResult.success("操作成功");
        } else {
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class}) //添加事务
    public AjaxResult audit(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        String id = params.getString("id");
        String auditReason = params.getString("auditreason");
        String status = params.getString("status");
        String reciver = params.getString("reciver");
        String centerid = params.getString("centerid");
        TlMaterialApplication tlMaterialApplication = tlMaterialApplicationMapper.selectById(id);
        tlMaterialApplication.setAuditperson(uid);
        tlMaterialApplication.setAudittime(new Date());
        tlMaterialApplication.setAuditreason(auditReason);
        tlMaterialApplication.setStatus(status);
        tlMaterialApplication.setRecivieperson(reciver);
        tlMaterialApplication.setCenterid(centerid);

        if (status.equals("1")) { //通过
            TlOutStorageCfg tlOutStorageCfg = new TlOutStorageCfg();
            tlOutStorageCfg.setId(StringUtils.uuid());
            tlOutStorageCfg.setStatus("0");
            tlOutStorageCfg.setSerialnumber(StringUtils.Serialnumber());
            tlOutStorageCfg.setStoragecenterid(centerid);
            tlOutStorageCfg.setMaterialnumber(tlMaterialApplication.getSerialnumber());
            tlOutStorageCfg.setReciveperson(reciver);
            tlOutStorageCfg.setItemtotalnum(tlMaterialApplication.getApplicationtotlnum());
            tlOutStorageCfg.setItemnum(tlMaterialApplication.getApplicationnum());
            tlOutStorageCfgMapper.insert(tlOutStorageCfg);
        } else if (status.equals("3")) { //废弃
            QueryWrapper<TlOutStorageCfg> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(TlOutStorageCfg::getMaterialnumber, tlMaterialApplication.getSerialnumber());
            String outstorageid = tlOutStorageCfgMapper.selectOne(queryWrapper).getId();
            if (!"".equals(outstorageid) || outstorageid != null) {
                tlOutStorageCfgMapper.deleteById(outstorageid);
            }
        }
        try {
            tlMaterialApplicationMapper.updateById(tlMaterialApplication);
            return AjaxResult.success("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败,请稍后再试");
        }
    }

    @Override
    public TlMaterialApplication getitemBySerialnumber(String Serialnumber) {
        QueryWrapper<TlMaterialApplication> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TlMaterialApplication::getSerialnumber, Serialnumber);
        TlMaterialApplication tlMaterialApplication = tlMaterialApplicationMapper.selectOne(queryWrapper);
        return tlMaterialApplication;
    }

    @Override
    public JSONObject getList(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
//        AuthoritySqlUtils authoritySqlUtils = new AuthoritySqlUtils();
        String antusql = authoritySqlUtils.GetAuthoritySqlByUid(uid, "createby", "deptid");

        Long page = StringUtils.isEmpty(params.getLong("page")) ? 1 : params.getLong("page");
        Long size = StringUtils.isEmpty(params.getLong("size")) ? 10 : params.getLong("size");
        JSONObject json = new JSONObject();
        Map map = new HashMap();

        map.put("applicationperson", params.getString("applicationperson"));
        map.put("serialnumber", params.getString("serialnumber"));
        map.put("starttime", params.getString("starttime"));
        map.put("endtime", params.getString("endtime"));
        map.put("auditperson", uid);
        map.put("antusql", antusql);
        map.put("status", params.getString("status"));


        Page<TlMaterialApplication> materalPage = new Page<>(page, size, true);
        IPage<TlMaterialApplication> iPage = tlMaterialApplicationMapper.listMaterialAppli(materalPage, map);

        json.put("total", iPage.getTotal());
        json.put("size", iPage.getSize());
        json.put("pages", iPage.getPages());
        json.put("current", iPage.getCurrent());
        json.put("materallist", iPage.getRecords());
        return json;
    }

    @Override
    public TlMaterialApplication getDetailById(JSONObject params) throws HssException {
        String id = params.getString("id");
        TlMaterialApplication tlMaterialApplication = tlMaterialApplicationMapper.selectById(id);
        QueryWrapper<TlOutStorageCfg> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TlOutStorageCfg::getMaterialnumber, tlMaterialApplication.getSerialnumber());
        List<TlMaterialDetail> tlMaterialDetails = tlMaterialDetailService.getitemListBySerialnumber(tlMaterialApplication.getSerialnumber());
        if (!tlMaterialDetails.isEmpty()) {
            tlMaterialApplication.setDateils(tlMaterialDetails);
        }
        return tlMaterialApplication;
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public AjaxResult deleteByid(JSONObject params) throws HssException {
        String id = params.getString("id");
        int i = tlMaterialApplicationMapper.deleteById(id);
        tlMaterialDetailService.deleteByMap(id);
        boolean flag = i > 0 ? true : false;
        if (flag) {
            return AjaxResult.success("操作成功");
        } else {
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }
}
